package com.chushouya.manager.dao.repository;

import com.chushouya.manager.constants.UserStatusEnum;
import com.chushouya.manager.dao.entity.UserEntity;
import com.chushouya.manager.dao.mapper.UserMapper;
import com.chushouya.manager.dto.admin.user.query.UserQuery;
import com.general.framework.core.lang.Strings;
import com.general.framework.core.schema.PageResult;
import com.general.framework.data.mybatis.BaseRepository;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Objects;

@Repository
public class UserRepository extends BaseRepository<UserMapper, UserEntity, Long> {

    private Example buildExample(UserQuery query) {
        final Example example = this.buildExample();
        if (Objects.nonNull(query.getUserId())) {
            example.and().andEqualTo("userId", query.getUserId());
        }
        if (Strings.isNotEmpty(query.getUserPhone())) {
            example.and().andEqualTo("userPhone", query.getUserPhone());
        }
        if (Objects.nonNull(query.getUserName())) {
            example.and().andEqualTo("userName", query.getUserName());
        }
        if (Objects.nonNull(query.getPartnerId())) {
            example.and().andEqualTo("partnerId", query.getPartnerId());
        }
        example.and().andEqualTo("status", UserStatusEnum.NORMAL.value());
        example.orderBy("userId").desc();
        return example;
    }

    private UserEntity selectOneByProperty(String property, Object value) {
        Example example = buildExample();
        example.and().andEqualTo(property, value);
        return this.selectFirstOneByExample(example);
    }

    public UserEntity selectOneWithProperties(Long userId, String... properties) {
        final Example example = this.buildExample();
        example.and().andEqualTo("userId", userId);
        example.selectProperties(properties);
        return super.selectFirstOneByExample(example);
    }

    public UserEntity selectOne(UserQuery query) {
        return super.selectFirstOneByExample(this.buildExample(query));
    }

    public List<UserEntity> selectList(UserQuery query) {
        return this.selectByExample(this.buildExample(query));
    }

    public PageResult<UserEntity> selectPageResult(UserQuery query) {
        return super.selectPage(query.getPageRequest(), this.buildExample(query));
    }

    public UserEntity selectByUserName(String userName) {
        return this.selectOneByProperty("userName", userName);
    }

    public UserEntity selectByUserPhone(String userPhone) {
        return this.selectOneByProperty("userPhone", userPhone);
    }

    public UserEntity selectByUserId(Long userId) {
        return this.selectOneByProperty("userId", userId);
    }

    public PageResult<UserEntity> selectUserPageResult(UserQuery query) {
        return super.selectPage(query.getPageRequest(), this.buildExample(query));
    }
}
